package cn.itcast.crm.dao.impl;


import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import cn.itcast.crm.dao.BaseDao;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
	private Class clazz;
	public BaseDaoImpl() {
		Type type = this.getClass().getGenericSuperclass();
		
		if (type instanceof ParameterizedType){
			ParameterizedType ptype =  (ParameterizedType) type;
			clazz = (Class) ptype.getActualTypeArguments()[0];
		}
	}

	@Override
	public void save(T t) {
		getHibernateTemplate().save(t);
		
	}

	@Override
	public void delete(T t) {
		getHibernateTemplate().delete(t);
		
	}

	@Override
	public void update(T t) {
		getHibernateTemplate().update(t);
		
	}

	@Override
	public List<T> findAll() {
		
		return (List<T>)getHibernateTemplate().loadAll(clazz);
	}

	@Override
	public T findById(Serializable id) {
		
		return (T)getHibernateTemplate().get(clazz, id);
	}
	
	@Override
	public int findCount(DetachedCriteria criteria) {
		criteria.setProjection(Projections.rowCount());
		
		List list =	getHibernateTemplate().findByCriteria(criteria);
		Long result = (Long)list.get(0);
		
		return result.intValue();
	}

	@Override
	public List<T> findPage(DetachedCriteria criteria, int currentPage, int pageSize) {
		criteria.setProjection(null);
		
		return (List<T>)getHibernateTemplate().findByCriteria(criteria, (currentPage-1)*pageSize, pageSize);
	}

}
